<template>
  <div>
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-input
          v-model="searchEmpNum"
          placeholder="请输入员工编号"
          style="width: 200px"
          class="filter-item"
        ></el-input>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="success" @click="handleAdd">添加薪资记录</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="empNum" label="员工编号" width="100"></el-table-column>
        <el-table-column label="基本工资" width="120">
          <template slot-scope="scope">
            {{ formatMoney(scope.row.basicSalary) }}
          </template>
        </el-table-column>
        <el-table-column label="绩效工资" width="120">
          <template slot-scope="scope">
            {{ formatMoney(scope.row.performanceSalary) }}
          </template>
        </el-table-column>
        <el-table-column label="奖金" width="120">
          <template slot-scope="scope">
            {{ formatMoney(scope.row.bonus) }}
          </template>
        </el-table-column>
        <el-table-column label="扣款" width="120">
          <template slot-scope="scope">
            <span style="color: #F56C6C">{{ formatMoney(scope.row.penalty) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总计" width="120">
          <template slot-scope="scope">
            <span style="color: #67C23A; font-weight: bold">
              {{ formatMoney(scope.row.totalSalary) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="发薪日期" width="120">
          <template slot-scope="scope">
            {{ formatDate(scope.row.salaryDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="info" @click="handleView(scope.row)">查看</el-button>
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="员工编号" prop="empNum" v-if="!isEdit">
          <el-input v-model.number="form.empNum"></el-input>
        </el-form-item>
        <el-form-item label="基本工资" prop="basicSalary">
          <el-input v-model.number="form.basicSalary"></el-input>
        </el-form-item>
        <el-form-item label="绩效工资" prop="performanceSalary">
          <el-input v-model.number="form.performanceSalary"></el-input>
        </el-form-item>
        <el-form-item label="奖金" prop="bonus">
          <el-input v-model.number="form.bonus"></el-input>
        </el-form-item>
        <el-form-item label="扣款" prop="penalty">
          <el-input v-model.number="form.penalty"></el-input>
        </el-form-item>
        <el-form-item label="发薪日期" prop="salaryDate">
          <el-date-picker
            v-model="form.salaryDate"
            type="datetime"
            placeholder="选择发薪日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm('form')">确定</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="薪资记录详情" :visible.sync="detailVisible" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="员工编号">{{ detail.empNum }}</el-descriptions-item>
        <el-descriptions-item label="基本工资">{{ formatMoney(detail.basicSalary) }}</el-descriptions-item>
        <el-descriptions-item label="绩效工资">{{ formatMoney(detail.performanceSalary) }}</el-descriptions-item>
        <el-descriptions-item label="奖金">{{ formatMoney(detail.bonus) }}</el-descriptions-item>
        <el-descriptions-item label="扣款">
          <span style="color: #F56C6C">{{ formatMoney(detail.penalty) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="总计">
          <span style="color: #67C23A; font-weight: bold">
            {{ formatMoney(detail.totalSalary) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="发薪日期">{{ formatDate(detail.salaryDate) }}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      tableData: [],
      searchEmpNum: '',
      dialogVisible: false,
      detailVisible: false,
      dialogTitle: '',
      isEdit: false,
      currentRecordId: null,
      detail: {},
      form: {
        empNum: '',
        basicSalary: '',
        performanceSalary: '',
        bonus: '',
        penalty: '',
        salaryDate: ''
      },
      rules: {
        empNum: [
          { required: true, message: '请输入员工编号', trigger: 'blur' },
          { type: 'number', message: '员工编号必须为数字', trigger: 'blur' }
        ],
        basicSalary: [
          { required: true, message: '请输入基本工资', trigger: 'blur' },
          { type: 'number', message: '请输入有效的基本工资' }
        ],
        performanceSalary: [
          { required: true, message: '请输入绩效工资', trigger: 'blur' },
          { type: 'number', message: '请输入有效的绩效工资' }
        ],
        bonus: [
          { required: true, message: '请输入奖金', trigger: 'blur' },
          { type: 'number', message: '请输入有效的奖金' }
        ],
        penalty: [
          { required: true, message: '请输入扣款', trigger: 'blur' },
          { type: 'number', message: '请输入有效的扣款' }
        ],
        salaryDate: [
          { required: true, message: '请选择发薪日期', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getAllRecords()
  },
  methods: {
    handleView(row) {
      this.detail = { ...row }
      this.detailVisible = true
    },
    formatMoney(value) {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(value)
    },
    formatDate(dateStr) {
      if (!dateStr) return ''
      return dateStr.split(' ')[0]
    },
    getAllRecords() {
      this.loading = true
      this.$http.get("/api/salary_records")
        .then(response => {
          if (response.data.code === 200) {
            this.tableData = response.data.data
          } else {
            this.$message.error(response.data.msg)
          }
        })
        .catch(error => {
          this.$message.error("获取数据失败：" + error.message)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSearch() {
      if (this.searchEmpNum) {
        this.$http.get(`/api/salary_records/${this.searchEmpNum}`)
          .then(response => {
            if (response.data.code === 200) {
              this.tableData = response.data.data
            } else {
              this.$message.error(response.data.msg)
            }
          })
      } else {
        this.getAllRecords()
      }
    },
    resetSearch() {
      this.searchEmpNum = ''
      this.getAllRecords()
    },
    handleAdd() {
      this.dialogVisible = true
      this.isEdit = false
      this.dialogTitle = '添加薪资记录'
      this.form = {
        empNum: '',
        basicSalary: '',
        performanceSalary: '',
        bonus: '',
        penalty: '',
        salaryDate: ''
      }
    },
    handleEdit(row) {
      this.dialogVisible = true
      this.isEdit = true
      this.dialogTitle = '编辑薪资记录'
      this.currentRecordId = row.recordId
      this.form = { ...row }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = JSON.stringify(this.form)
          const headers = {
            'Content-Type': 'application/json'
          }

          if (this.isEdit) {
            this.$http.put(`/api/salary_records/${this.currentRecordId}`, data, { headers })
              .then(response => {
                if (response.data.code === 200) {
                  this.$message.success('更新成功')
                  this.dialogVisible = false
                  this.getAllRecords()
                } else {
                  this.$message.error(response.data.msg)
                }
              })
              .catch(error => {
                this.$message.error('更新失败：' + error.message)
              })
          } else {
            this.$http.post('/api/salary_records', data, { headers })
              .then(response => {
                if (response.data.code === 200) {
                  this.$message.success('添加成功')
                  this.dialogVisible = false
                  this.getAllRecords()
                } else {
                  this.$message.error(response.data.msg)
                }
              })
              .catch(error => {
                this.$message.error('添加失败：' + error.message)
              })
          }
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该薪资记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/api/salary_records/${row.recordId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功')
              this.getAllRecords()
            } else {
              this.$message.error(response.data.msg)
            }
          })
          .catch(error => {
            this.$message.error('删除失败：' + error.message)
          })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.search-box {
  margin-bottom: 20px;
}
.filter-item {
  margin-right: 10px;
}
</style>
